﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;
using PengSW.SignalHelper;

namespace PengSW.SignalUi
{
    /// <summary>
    /// SignalLight.xaml 的交互逻辑
    /// </summary>
    public partial class SignalLight : UserControl
    {
        public static readonly DependencyProperty IntervalProperty = DependencyProperty.Register("Interval", typeof(int), typeof(SignalLight), new PropertyMetadata(100));
        public int Interval
        {
            get { return (int)GetValue(IntervalProperty); }
            set { SetValue(IntervalProperty, value); }
        }

        public SignalLight()
        {
            InitializeComponent();

            _Timer.Tick += OnTimer_Tick;
        }

        private void OnSignal_SignalDisable(object sender, EventArgs e)
        {
            DisableSignal();
        }

        private void OnSignal_SignalEnable(object sender, EventArgs e)
        {
            EnableSignal();
        }

        private void OnTimer_Tick(object sender, EventArgs e)
        {
            DisableSignal();
        }

        public void EnableSignal()
        {
            Dispatcher.Invoke(() =>
            {
                Light.Fill = Brushes.Lime;
                if (Interval > 0)
                {
                    _Timer.Interval = TimeSpan.FromMilliseconds(Interval);
                    _Timer.Start();
                }
            });
        }

        public void DisableSignal()
        {
            Dispatcher.Invoke(() =>
            {
                Light.Fill = Brushes.LightGray;
                _Timer.Stop();
            });
        }

        private readonly DispatcherTimer _Timer = new DispatcherTimer();

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue is ISignalable aOldSignal)
            {
                aOldSignal.SignalEnable -= OnSignal_SignalEnable;
                aOldSignal.SignalDisable -= OnSignal_SignalDisable;
            }
            if (e.NewValue is ISignalable aNewSignal)
            {
                aNewSignal.SignalEnable += OnSignal_SignalEnable;
                aNewSignal.SignalDisable += OnSignal_SignalDisable;
            }
        }
    }
}
